import { Injectable, Logger } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import { User } from '@prisma/client';

@Injectable()
export class AuthService {
  private readonly logger = new Logger(AuthService.name);

  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    this.logger.log(`尝试验证用户: ${username}`);
    const user = await this.usersService.validateUser(username, password);
    if (user) {
      this.logger.log(`用户验证成功: ${username}`);
      const { password, ...result } = user;
      return result;
    }
    this.logger.warn(`用户验证失败: ${username}`);
    return null;
  }

  async login(user: User) {
    this.logger.log(`用户登录: ${user.username}`);
    const payload = { username: user.username, sub: user.id, role: user.role };
    const result = {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
      },
    };
    this.logger.log(`用户登录成功: ${user.username}`);
    return result;
  }

  async register(userData: { username: string; email: string; password: string; role?: string }) {
    const role = userData.role || 'STUDENT';
    this.logger.log(`新用户注册: ${userData.username}, 邮箱: ${userData.email}, 角色: ${role}`);
    const user = await this.usersService.createUser({
      ...userData,
      role: role
    });
    this.logger.log(`用户注册成功: ${userData.username}, 角色: ${role}`);
    return this.login(user);
  }
}